package com.itheima.stock.remotedata;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.stock.common.constance.JsonConstance;
import com.itheima.stock.job.service.StockTimerService;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockMarketLogPriceMapper;
import com.itheima.stock.pojo.StockMarketIndexInfo;
import com.itheima.stock.pojo.StockMarketLogPrice;
import com.itheima.stock.pojo.StockRtInfo;
import com.itheima.stock.uitls.IdWorker;
import com.itheima.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@SpringBootTest
public class PullRemoteData1 {

    @Autowired
    private StockTimerService stockTimerService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;

    @Autowired
    private StockMarketLogPriceMapper stockMarketLogPriceMapper;


    //拉取股票代码
    @Test
    public void test01() throws ParseException {
        List<String> codeList = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            List<String> list = parseStockCode(i + "", 30 + "");
            if(list!=null&list.size() > 0){
                codeList.addAll(list);
            }
        }
        System.out.println(codeList);
    }

    public  List<String> parseStockCode(String pagenum,String pagesize) throws ParseException {
        List<String> codeList = new ArrayList<>();
        String host = "https://jsapigpcx.market.alicloudapi.com";
        String path = "/stock/list";
        String method = "GET";
        String appcode = "0532eaea2ffd4a43a2d7662317784433";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("classid", "1");
        //当前页
        querys.put("pagenum", pagenum);
        //每页显示条数
        querys.put("pagesize", pagesize);


        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            String resultJson = EntityUtils.toString(response.getEntity());
            //解析数据
            Map map = JSON.parseObject(resultJson, Map.class);
            Map map1 = JSON.parseObject(map.get("result").toString(), Map.class);
            JSONArray jsonArray=(JSONArray) map1.get("list");
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                String code = jsonObject.get("code").toString();
                String name = jsonObject.get("name").toString();
                System.out.println(name+":"+code);
                codeList.add(code);
            }
            return codeList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //个股数据解析
    @Test
    public void test02() throws Exception {
        Map codeData = parseStockCodeData("003032");
        insertBatch2();

    }


    public Map parseStockCodeData(String code) throws Exception {
        String host = "https://jsapigpcx.market.alicloudapi.com";
        String path = "/stock/query";
        String method = "GET";
        String appcode = "0532eaea2ffd4a43a2d7662317784433";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("code", code);


        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
        System.out.println(response.toString());
        //获取response的body
        //System.out.println(EntityUtils.toString(response.getEntity()));
        //解析数据
        String resultJson2 = EntityUtils.toString(response.getEntity());
        Map map = JSON.parseObject(resultJson2, Map.class);
        //Map map1 = JSON.parseObject(map.get("result").toString(), Map.class);
        JSONArray jsonArray = (JSONArray) map.get("result");
        //遍历个股数组
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject) o;
            //个股代码
            String sockCode = jsonObject.get("code").toString();
            System.out.println("个股代码 :" + sockCode);
            //当前时间
            String curtime = jsonObject.get("updatetime").toString();
            System.out.println("当前时间 :" + curtime);
            //个股名称
            String stockname = jsonObject.get("name").toString();
            System.out.println("个股名称 :" + stockname);
            //当前价格
            String curprice = jsonObject.get("price").toString();
            System.out.println("当前价格 :" + curprice);
            BigDecimal curprice1 = new BigDecimal(curprice);
            //前收盘价
            BigDecimal lastclosingprice = (BigDecimal) jsonObject.get("lastclosingprice");
            System.out.println("前收盘价 : " + lastclosingprice);

            JSONArray trendArray = (JSONArray) jsonObject.get("trend");
            for (Object obj : trendArray) {
                StockRtInfo stockRtInfo = new StockRtInfo();
                // 将每一分钟生成的数据转成字符串
                String trend = (String) obj;
                // 处理
                String[] trendArr = trend.split(",");
                String curTime = trendArr[0];
                String tradeAmount =trendArr[2];
                String tradeVolume1=trendArr[3];
                BigDecimal tradeVolume = new BigDecimal(tradeVolume1);

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date date = dateFormat.parse(curTime);
                stockRtInfo.setId(idWorker.nextId()+"");
                stockRtInfo.setStockCode(sockCode);
                stockRtInfo.setCurTime(curtime);
                stockRtInfo.setPreClosePrice(lastclosingprice);
                stockRtInfo.setOpenPrice(curprice1);
                stockRtInfo.setTradeAmount(tradeAmount);
                stockRtInfo.setTradeVolume(tradeVolume);
                stockRtInfo.setCurPrice(curprice1);
                stockRtInfo.setMaxPrice(null);
                stockRtInfo.setMinPrice(null);
                map.put("stockRtInfo",stockRtInfo);

            }
        }
        return map;
    }


    //个股存储 ----有问题，应该存map集合到数据库中

    public void insertBatch2() throws Exception {
        List<String> codeList = new ArrayList<>();
    /*for (int i = 1; i <= 5; i++) {
        List<String> list = parseStockCode(i, 30);
        if (list!=null && list.size()>0){
            codeList.addAll(list); }
    }*/
        codeList.add("003032");
        List<StockRtInfo>lists=new ArrayList<>();
        for (String s : codeList) {
            Map stockRtlist = parseStockCodeData(s);
            lists.addAll((Collection<? extends StockRtInfo>) stockRtlist);
        }
    }



}
